<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <!-- 左侧记录 -->
        <span slot="before">共{{ page.total }}条记录</span>
        <!-- 左侧记录 -->

        <!-- 右侧按钮 -->
        <template #after>
          <el-button size="small" type="success" @click="$router.push('/import')">excel导入</el-button>
          <el-button size="small" type="danger" @click="exportData">excel导出</el-button>
          <el-button size="small" type="primary" :disabled="!checkPermission('POINT-USER-ADD')" @click="showDialog = true">新增员工</el-button>
        </template>
        <!-- 右侧按钮 -->
      </PageTools>

      <!-- 表格组件 -->
      <el-table v-loading="loading" border :data="list">
        <el-table-column type="index" width="50px" label="序号" />
        <el-table-column label="姓名" sortable prop="username" />
        <el-table-column width="120px" label="头像">
          <!-- 员工头像 -->
          <template v-slot="{ row }">
            <img
              v-imagerror="require('@/assets/common/wawa.jpeg')"
              :src="row.staffPhoto"
              style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
              @click="chowQrCode(row.staffPhoto)"
            >
          </template>
          <!-- /员工头像 -->
        </el-table-column>
        <el-table-column label="工号" sortable prop="workNumber" />
        <el-table-column label="聘用形式" :formatter="formatEmployment" sortable prop="formOfEmployment" />
        <el-table-column label="部门" sortable prop="departmentName" />
        <el-table-column label="入职时间" sortable prop="timeOfEntry">
          <template slot-scope="{row}">
            {{ row.timeOfEntry | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="账户状态" sortable prop="enableState">
          <template v-slot="{row}">
            <el-switch :value="row.enableState === undefined" />
          </template>
        </el-table-column>
        <el-table-column label="操作" sortable fixed="right" width="280">
          <template slot-scope="{ row }">
            <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
            <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格组件 -->

      <!-- 分页 -->
      <el-row type="flex" justify="center" align="middle" style="heigth:60px">
        <el-pagination
          :current-page="page.page"
          :page-size="page.size"
          :total="page.total"
          layout="prev, pager, next"
          @current-change="chengePage"
        />
      </el-row>
      <!-- 分页 -->
    </div>

    <!-- 添加弹层 -->
    <AddEmployee :show-dialog.sync="showDialog" />
    <!-- /添加弹层 -->

    <!-- 二维码弹层 -->
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- /二维码弹层 -->

    <!-- 分配权限组件 -->
    <AssignRole
      ref="assignRole"
      :show-role-dialog="showRoleDialog"
      :user-id="userId"
      @close="close"
    />
    <!-- /分配权限组件 -->
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      loading: false,
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: null
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    close() {
      this.showRoleDialog = false
    },
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    chengePage(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    formatEmployment(row, column, cellValue, index) { // 格式化聘用形式
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    async delEmployee(id) {
      try {
        await this.$confirm('确定删除?')
        await delEmployee(id)
        this.$message.success('成功')
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    },
    exportData() { // 导出excel
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeeList({ page: '1', size: this.page.total })
        const data = this.formatJson(headers, rows)
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          bookType: 'txt',
          multiHeader,
          merges
        })
      })
    },
    formatJson(headers, rows) {
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    chowQrCode(url) {
      if (url) {
        this.showCodeDialog = true
        this.$nextTick(() => { // 等待页面渲染完执行转换二维码
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转换成二维码
        })
      } else {
        this.$message.error('未上传头像')
      }
    },
    async editRole(id) {
      this.userId = id
      await this.$refs.assignRole.getUserDateilById(id)
      this.showRoleDialog = true
    }
  }
}
</script>

<style>

</style>
